package com.ysq.www.api.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ysq.www.api.user.entity.GiveLike;
import com.ysq.www.api.user.mapper.GiveLikeMapper;
import com.ysq.www.api.user.service.IGiveLikeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ysq.www.common.result.ResultMsg;
import com.ysq.www.common.utils.Comm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 点赞记录表 服务实现类
 * </p>
 *
 * @author dql
 * @since 2020-09-07
 */
@Service
public class GiveLikeServiceImpl extends ServiceImpl<GiveLikeMapper, GiveLike> implements IGiveLikeService {

    @Autowired
    private GiveLikeMapper giveLikeMapper;

    /**
     * 点赞/取消点赞
     * @param userId 用户id
     * @param contentId 内容id
     * @param type 点赞类型：1资讯
     * @param isLike 0取消点赞，1点赞
     * @return ResultMsg
     */
    @Override
    public ResultMsg addOrUpdateById(Integer userId, Integer contentId, Integer type, Integer isLike) {
        //点赞
        if (isLike == 1){
            //先查询是否有记录存在
            QueryWrapper<GiveLike> wrapper = new QueryWrapper<>();
            wrapper.eq("content_id",contentId).eq("type",type).eq("user_id",userId);
            GiveLike gl = this.getOne(wrapper);
            if (gl != null){
                gl.setStatus(0);
                gl.setUpdateTime(Comm.getNow());
                this.updateById(gl);
            }else {
                GiveLike ngl = new GiveLike();
                ngl.setUserId(userId);
                ngl.setType(type);
                ngl.setContentId(contentId);
                ngl.setCreateTime(Comm.getNow());
                ngl.setUpdateTime(Comm.getNow());
                ngl.setStatus(0);
                this.save(ngl);
            }
        }else if (isLike == 0){
            UpdateWrapper<GiveLike> wrapper = new UpdateWrapper<>();
            wrapper.set("status",1).eq("type",type).
                    eq("content_id",contentId).eq("user_id",userId);
            this.update(null,wrapper);
        }
        return ResultMsg.UPDATE_SUCCESS.setNewMsg("操作成功");
    }
}
